#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>


#include "spinlock.h"

struct Semaphore
{
  spinlock_t spinlock;
  int count;
  int (*func)(void);
};

typedef struct Semaphore * semaphore;


semaphore semaphore_create(int n, int (*func)(void))
{
  semaphore sem = malloc(sizeof(struct Semaphore));
  sem->count = n;
  sem->func = func;
  sem->spinlock.lock = 0;
  return sem;
}

//Proberen "Puis je"
int P(semaphore s){
  spinlock_t lock = s->spinlock;
  while(1){
		if(spin_trylock(&lock)==0){
			if(s->count > 0){
				s->count--;
				spin_unlock(&lock);
				return 0;
			}
		spin_unlock(&lock);
		}
	if(s->func != NULL)
		s->func();
    }
}

//Verhogen "vas y"
int V(semaphore s){
  while(1){
      if(spin_trylock(&s->spinlock)==0){
		s->count++;
		spin_unlock(&s->spinlock);
		return 0;
	}
    if(s->func != NULL)
		s->func();
    }
}

